﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.IO.Ports;

namespace wf_sereial_enum
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate void FreshUIDelegate();
        private FreshUIDelegate FreshUI;
        private List<EnumSerialPort> ports = null;
        private IList<string> serial_displays = null;
        //private USBEventWatcher usbWatcher = null;
        private void RefreshSerials()
        {
            IList<string> list = new List<string>();
            ports = EnumSerialPort.GetPorts();

            foreach (EnumSerialPort port in ports)
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(port.Name);
                sb.Append("  -  ");
                sb.Append(port.Des);
                //sb.Append("  -  ");
                //using (SerialPort serial = new SerialPort(port.Name))
                //{
                //    if (serial.IsOpen)
                //    {
                //        sb.Append("Opened");
                //    }
                //    else
                //    {
                //        sb.Append("Closed");
                //    }
                //}
                list.Add(sb.ToString());
            }

            serial_displays = list;
        }

        private void fresh_ui_seials()
        {

            RefreshSerials();
            listBox_serials.Items.Clear();
            foreach (String s in serial_displays)
            {
                listBox_serials.Items.Add(s);
            }
        }

        private void btn_fresh_Click(object sender, EventArgs e)
        {
            fresh_ui_seials();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fresh_ui_seials();
            //usbWatcher = new USBEventWatcher();
            //usbWatcher.updateDelegate = on_usb_change;
            FreshUI = SerialEnumFresh;
            if (checkBox_AutoFresh.Checked)
            {
                timer_refresh.Enabled = true;
                //usbWatcher.register();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkBox_AutoFresh.Checked)
            {
                timer_refresh.Enabled = false;
                //usbWatcher.stop();
            }
        }

        private void checkBox_AutoFresh_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_AutoFresh.Checked)
            {
                //usbWatcher.register();
                timer_refresh.Enabled = true;
            }
            else
            {
                timer_refresh.Enabled = false;
                //usbWatcher.stop();
            }
        }

        void SerialEnumFresh()
        {
            fresh_ui_seials();
        }

        private void on_usb_change(string data)
        {
            this.Invoke(FreshUI);
        }

        private void timer_refresh_Tick(object sender, EventArgs e)
        {
            this.Invoke(FreshUI);
        }
    }
    public class EnumSerialPort
    {
        /// <summary>
        /// 串口号
        /// </summary>
        public string Name { get; protected set; }
        /// <summary>
        /// 描述
        /// </summary>
        public string Des { get; protected set; }
        /// <summary>
        /// 制造商
        /// </summary>
        public string Manu { get; protected set; }

        public override string ToString()
        {
            return Name + " - " + Des;
        }

        /// <summary>
        /// 获取串口们
        /// </summary>
        public static List<EnumSerialPort> GetPorts()
        {
            List<EnumSerialPort> back = new List<EnumSerialPort>();
            
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity")) //调用WMI，获取Win32_PnPEntity，即所有设备
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if ((hardInfo.Properties["Name"].Value != null) &&
                        (hardInfo.Properties["Name"].Value.ToString().Contains("COM"))) //筛选出名称中包含COM的
                    {
                        EnumSerialPort temp = new EnumSerialPort();
                        string s = hardInfo.Properties["Name"].Value.ToString(); //获取名称
                        int p = s.LastIndexOf('(');
                        temp.Des = s.Substring(0, p); //截取描述（名称）
                        temp.Name = s.Substring(p + 1, s.Length - p - 2); //截取串口号
                        temp.Manu = hardInfo.Properties["Manufacturer"].Value.ToString(); //获取制造商
                        back.Add(temp);
                    }
                }
                searcher.Dispose();
            }

            return back;
        }
    }

    //public class USBEventWatcher
    //{
    //    private ManagementEventWatcher managementEventWatcherCreate;
    //    private ManagementEventWatcher managementEventWatcherDelete;
    //    private ManagementEventWatcher managementEventWatcher;

    //    public delegate void UpdateListBoxDelegate(string data);
    //    public UpdateListBoxDelegate updateDelegate;

    //    public void register()
    //    {
    //        // Create event query to be notified within 1 second of 
    //        // a change in a service
    //        WqlEventQuery queryCreate =
    //            new WqlEventQuery("__InstanceCreationEvent",
    //            new TimeSpan(0, 0, 2),
    //            "TargetInstance ISA 'Win32_Process'");
    //        WqlEventQuery queryDelete =
    //            new WqlEventQuery("__InstanceDeletionEvent",
    //            new TimeSpan(0, 0, 5),
    //            "TargetInstance ISA 'Win32_Process'");

    //        //managementEventWatcherCreate = new ManagementEventWatcher(queryCreate);
    //        //managementEventWatcherDelete = new ManagementEventWatcher(queryDelete);

    //        managementEventWatcher = new ManagementEventWatcher("Select * From __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA \"Win32_DiskDrive\"");
    //        managementEventWatcher.EventArrived += new EventArrivedEventHandler(managementEventWatcher_EventArrived);
    //        managementEventWatcher.Start();

    //        //managementEventWatcherCreate.EventArrived += new EventArrivedEventHandler(managementEventWatcher_EventArrived);
    //        //managementEventWatcherDelete.EventArrived += new EventArrivedEventHandler(managementEventWatcher_EventArrived);


    //        //managementEventWatcherCreate.Start();
    //        //managementEventWatcherDelete.Start();
    //    }
        
    //    public void stop()
    //    {
    //        //managementEventWatcherCreate.Stop();
    //        //managementEventWatcherDelete.Stop();
    //        managementEventWatcher.Stop();
    //    }

    //    public void start()
    //    {
    //        //managementEventWatcherCreate.Start();
    //        //managementEventWatcherDelete.Start();
    //        managementEventWatcher.Start();
    //    }

    //    private void managementEventWatcher_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
    //    {
    //        ManagementBaseObject newEvent = e.NewEvent, newEventTarget = (newEvent["TargetInstance"] as ManagementBaseObject);
    //        //if (newEventTarget["InterfaceType"].ToString() == "USB")
    //        //{
    //        switch (newEvent.ClassPath.ClassName)
    //        {
    //            case "__InstanceCreationEvent":
    //                updateDelegate("in");
    //                break;
    //            case "__InstanceDeletionEvent":
    //                updateDelegate("out");
    //                break;
    //        }
    //        //}
    //    }
    //}
}
